package com.example.springsecurity.config;

import com.example.springsecurity.handler.LoginFailureHandler;
import com.example.springsecurity.handler.LoginSuccessHandler;
import com.example.springsecurity.security.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SpringSocialConfigurer;


@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private LoginFailureHandler failureHandler;

    @Autowired
    private LoginSuccessHandler successHandler;

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private SmsSecurityConfig smsSecurityConfig;

    @Autowired
    private SpringSocialConfigurer springSocialConfigurer;


    //重写该方法 : 自定义配置过滤规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http
                .apply(springSocialConfigurer)
                .and()
                .formLogin()//表单登录
                .loginPage("/login.html")//指定自己的登陆页面
                .loginProcessingUrl("/authentication/login")//配置登录接口路径，需要与页面form表单的action保持一致 告诉security处理该路径
//                .defaultSuccessUrl("/success",true)//登陆成功跳转页面
//                .failureUrl("/failure")//登陆失败跳转页面
                .successHandler(successHandler)//设置登陆成功后的处理器
                .failureHandler(failureHandler)//设置登陆失败后的处理器
                .and()
                .authorizeRequests()//配置权限
                .antMatchers("/login.html","/failure","/code/*","/auth/qq").permitAll()//指定所有用户进行访问指定的url
                .anyRequest()//任何请求
                .authenticated()//都需要身份认证
                .and()
                .csrf().disable()//关闭跨域
                .apply(smsSecurityConfig);//把smsSecurityConfig配置加进来


    }

    //可以配置用户名和密码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);//使用自定义的myUserDetailsService类
    }

    //配置前端资源是否放过
    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }
}
